<template>
	<view class="container">
		<!-- Header -->
		<view class="header">
			<view class="title">我的访客预约</view>
			<view class="add-btn" @click="navigateToCreate">
				<text class="iconfont icon-add"></text>
				<text>新增预约</text>
			</view>
		</view>
		
		<!-- Filter -->
		<view class="filter-box">
			<view class="filter-item">
				<picker :range="statusOptions" @change="statusChange">
					<view class="picker">
						<text>状态: {{ currentStatus || '全部' }}</text>
						<text class="iconfont icon-down"></text>
					</view>
				</picker>
			</view>
			<view class="filter-item">
				<picker mode="date" :value="filterDate" @change="dateChange">
					<view class="picker">
						<text>日期: {{ filterDate || '全部' }}</text>
						<text class="iconfont icon-calendar"></text>
					</view>
				</picker>
			</view>
		</view>
		
		<!-- Appointment List -->
		<view class="appointment-list">
			<!-- Loading -->
			<view class="loading" v-if="loading">
				<image src="/static/images/loading.gif"></image>
				<text>加载中...</text>
			</view>
			
			<!-- Empty -->
			<view class="empty" v-else-if="appointmentList.length === 0">
				<image src="/static/images/empty.png"></image>
				<text>暂无预约记录</text>
			</view>
			
			<!-- List -->
			<view v-else>
				<view 
					class="appointment-item" 
					v-for="item in appointmentList" 
					:key="item.appointment_id"
					@click="navigateToDetail(item.appointment_id)"
				>
					<view class="item-header">
						<view class="visitor-info">
							<text class="visitor-name">{{ item.visitor?.name || '未知访客' }}</text>
							<text class="visitor-phone">{{ item.visitor?.phone || '' }}</text>
						</view>
						<view class="status" :class="getStatusClass(item.status)">
							{{ getStatusText(item.status) }}
						</view>
					</view>
					<view class="item-body">
						<view class="info-row">
							<text class="label">预约时间</text>
							<text class="value">{{ formatDateTime(item.expected_visit_time) }}</text>
						</view>
						<view class="info-row">
							<text class="label">来访目的</text>
							<text class="value purpose">{{ item.visit_purpose }}</text>
						</view>
					</view>
					<view class="item-footer">
						<text class="time">创建时间: {{ formatDateTime(item.created_at) }}</text>
					</view>
				</view>
				
				<!-- Load More -->
				<view class="load-more" v-if="appointmentList.length > 0">
					<text v-if="loadMoreStatus === 'loading'">加载中...</text>
					<text v-else-if="loadMoreStatus === 'noMore'">没有更多了</text>
					<text v-else @click="loadMore">点击加载更多</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { visitorAppointmentAPI } from '@/api/services.js';

export default {
	data() {
		return {
			loading: false,
			appointmentList: [],
			page: 1,
			pageSize: 10,
			total: 0,
			loadMoreStatus: 'more', // more, loading, noMore
			statusOptions: ['全部', '待审批', '已批准', '已拒绝', '已入园', '已离园', '已取消'],
			statusDisplayMap: {
				0: '待审批',
				1: '已批准',
				2: '已拒绝',
				3: '已入园',
				4: '已离园',
				5: '已取消',
				'pending': '待审批',
				'approved': '已批准',
				'rejected': '已拒绝',
				'visited': '已入园',
				'cancelled': '已取消'
			},
			currentStatus: '',
			filterDate: '',
			needRefresh: false // 添加需要刷新的标志
		};
	},
	
	onLoad() {
		// 页面加载时获取预约列表
		this.getAppointmentList();
		
		// 添加事件监听器，用于刷新列表
		uni.$on('refreshAppointmentList', this.handleRefresh);
	},
	
	onUnload() {
		// 页面卸载时移除事件监听器
		uni.$off('refreshAppointmentList', this.handleRefresh);
	},
	
	onShow() {
		// 页面显示时，如果需要刷新，则刷新数据
		console.log('列表页面显示，检查是否需要刷新');
		
		// 从全局存储中获取刷新标志
		const globalRefresh = uni.getStorageSync('appointmentListNeedRefresh');
		if (globalRefresh || this.needRefresh) {
			console.log('需要刷新列表数据');
			this.getAppointmentList();
			// 重置刷新标志
			this.needRefresh = false;
			uni.removeStorageSync('appointmentListNeedRefresh');
		}
	},
	
	methods: {
		// 获取预约列表
		getAppointmentList(isLoadMore = false) {
			console.log('开始获取预约列表, isLoadMore:', isLoadMore);
			
			if (!isLoadMore) {
				this.page = 1;
				this.loading = true;
			}
			
			// 构建查询参数
			const params = {
				page: this.page,
				pageSize: this.pageSize
			};
			
			// 添加筛选条件
			if (this.currentStatus) {
				params.status = this.currentStatus;
			}
			
			if (this.filterDate) {
				params.date = this.filterDate;
			}
			
			console.log('预约列表查询参数:', params);
			
			// 使用新的API端点获取当前用户关联的访客预约
			visitorAppointmentAPI.getMyAppointments(params)
				.then(res => {
					console.log('我的预约列表响应:', res);
					if (res.code === 200 && res.data) {
						if (isLoadMore) {
							this.appointmentList = [...this.appointmentList, ...res.data.list];
						} else {
							this.appointmentList = res.data.list;
						}
						this.total = res.data.total;
						
						console.log('更新后的预约列表:', this.appointmentList.length, '条记录');
						
						// 更新加载更多状态
						if (this.appointmentList.length >= this.total) {
							this.loadMoreStatus = 'noMore';
						} else {
							this.loadMoreStatus = 'more';
						}
					} else {
						uni.showToast({
							title: res.message || '获取预约列表失败',
							icon: 'none'
						});
					}
				})
				.catch(err => {
					console.error('获取预约列表失败:', err);
					
					// 如果是连接问题，使用本地数据
					if (err.errMsg && err.errMsg.includes('request:fail')) {
						// 从本地缓存获取预约数据
						const localAppointments = uni.getStorageSync('localAppointments') || [];
						
						// 应用过滤条件
						let filteredAppointments = [...localAppointments];
						
						if (this.currentStatus) {
							filteredAppointments = filteredAppointments.filter(
								item => item.status === this.currentStatus
							);
						}
						
						if (this.filterDate) {
							filteredAppointments = filteredAppointments.filter(
								item => item.expected_visit_time.startsWith(this.filterDate)
							);
						}
						
						// 分页处理
						const start = (this.page - 1) * this.pageSize;
						const end = start + this.pageSize;
						
						if (isLoadMore) {
							this.appointmentList = [...this.appointmentList, ...filteredAppointments.slice(start, end)];
						} else {
							this.appointmentList = filteredAppointments.slice(start, end);
						}
						
						this.total = filteredAppointments.length;
						
						// 更新加载更多状态
						if (this.appointmentList.length >= this.total) {
							this.loadMoreStatus = 'noMore';
						} else {
							this.loadMoreStatus = 'more';
						}
						
						// 提示用户正在使用本地数据
						uni.showToast({
							title: '使用本地缓存数据',
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: '获取预约列表失败',
							icon: 'none'
						});
					}
				})
				.finally(() => {
					this.loading = false;
					uni.stopPullDownRefresh();
				});
		},
		
		// 加载更多
		loadMore() {
			if (this.loadMoreStatus === 'noMore') return;
			
			this.page++;
			this.loadMoreStatus = 'loading';
			this.getAppointmentList(true);
		},
		
		// 状态筛选
		statusChange(e) {
			const index = e.detail.value;
			const selectedStatus = this.statusOptions[index];
			if (selectedStatus === '全部') {
				this.currentStatus = '';
			} else {
				// 将中文状态转换为数字状态码
				const statusValues = {
					'待审批': 0,
					'已批准': 1,
					'已拒绝': 2,
					'已入园': 3,
					'已离园': 4,
					'已取消': 5
				};
				this.currentStatus = statusValues[selectedStatus];
			}
			this.getAppointmentList();
		},
		
		// 日期筛选
		dateChange(e) {
			this.filterDate = e.detail.value;
			this.getAppointmentList();
		},
		
		// 跳转到详情页
		navigateToDetail(id) {
			uni.navigateTo({
				url: `/pages/appointment/detail?id=${id}`
			});
		},
		
		// 跳转到创建页
		navigateToCreate() {
			uni.navigateTo({
				url: '/pages/appointment/create'
			});
		},
		
		// 获取状态样式
		getStatusClass(status) {
			// 数字状态码映射
			const statusMap = {
				0: 'status-pending',    // 待审批
				1: 'status-approved',   // 已批准
				2: 'status-rejected',   // 已拒绝
				3: 'status-entered',    // 已入园
				4: 'status-left',       // 已离园
				5: 'status-cancelled'   // 已取消
			};
			
			// 如果是数字状态码，直接映射
			if (typeof status === 'number' && statusMap[status]) {
				return statusMap[status];
			}
			
			// 如果是字符串状态，使用原有映射
			switch (status) {
				case 'pending':
					return 'status-pending';
				case 'approved':
					return 'status-approved';
				case 'rejected':
					return 'status-rejected';
				case 'visited':
					return 'status-entered';
				case 'cancelled':
					return 'status-cancelled';
				default:
					return '';
			}
		},
		
		// 获取状态文本
		getStatusText(status) {
			return this.statusDisplayMap[status] || status;
		},
		
		// 格式化日期时间
		formatDateTime(datetime) {
			if (!datetime) return '';
			
			try {
				const date = new Date(datetime);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			} catch (error) {
				console.error('日期格式化错误:', error);
				return datetime;
			}
		},
		
		// 处理刷新事件
		handleRefresh() {
			console.log('收到刷新列表事件');
			// 设置刷新标志，而不是直接刷新
			this.needRefresh = true;
			// 同时设置全局刷新标志，以防页面已经卸载
			uni.setStorageSync('appointmentListNeedRefresh', true);
			
			// 如果当前页面可见，则立即刷新
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			if (currentPage && currentPage.route && currentPage.route.includes('appointment/list')) {
				console.log('当前页面是列表页面，立即刷新');
				this.getAppointmentList();
			}
		}
	},
	// 下拉刷新
	onPullDownRefresh() {
		this.getAppointmentList();
	},
	// 上拉加载更多
	onReachBottom() {
		if (this.appointmentList.length < this.total) {
			this.loadMore();
		}
	}
};
</script>

<style lang="scss">
.container {
	padding: 20rpx;
	background-color: #F8F8F8;
	min-height: 100vh;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
	}
	
	.add-btn {
		display: flex;
		align-items: center;
		background-color: #007AFF;
		color: #FFFFFF;
		padding: 12rpx 24rpx;
		border-radius: 30rpx;
		font-size: 28rpx;
		
		.iconfont {
			margin-right: 8rpx;
		}
	}
}

.filter-box {
	background-color: #FFFFFF;
	border-radius: 16rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	
	.filter-item {
		margin-bottom: 20rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.picker {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 16rpx 0;
			border-bottom: 1px solid #EEEEEE;
		}
	}
}

.appointment-list {
	.loading, .empty {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		
		image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;
		}
		
		text {
			color: #999999;
			font-size: 28rpx;
		}
	}
	
	.appointment-item {
		background-color: #FFFFFF;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		
		.item-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;
			
			.visitor-info {
				.visitor-name {
					font-size: 32rpx;
					font-weight: bold;
					margin-right: 16rpx;
				}
				
				.visitor-phone {
					font-size: 28rpx;
					color: #666666;
				}
			}
			
			.status {
				padding: 8rpx 16rpx;
				border-radius: 30rpx;
				font-size: 24rpx;
				
				&.status-pending {
					background-color: #FFF3E0;
					color: #FF9800;
				}
				
				&.status-approved {
					background-color: #E0F7FA;
					color: #00BCD4;
				}
				
				&.status-rejected {
					background-color: #FFEBEE;
					color: #F44336;
				}
				
				&.status-entered {
					background-color: #E8F5E9;
					color: #4CAF50;
				}
				
				&.status-left {
					background-color: #F5F5F5;
					color: #9E9E9E;
				}
				
				&.status-cancelled {
					background-color: #F5F5F5;
					color: #9E9E9E;
				}
			}
		}
		
		.item-body {
			.info-row {
				display: flex;
				margin-bottom: 12rpx;
				
				.label {
					width: 160rpx;
					color: #666666;
					font-size: 28rpx;
				}
				
				.value {
					flex: 1;
					font-size: 28rpx;
					
					&.purpose {
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						overflow: hidden;
						text-overflow: ellipsis;
					}
				}
			}
		}
		
		.item-footer {
			margin-top: 20rpx;
			padding-top: 16rpx;
			border-top: 1px solid #EEEEEE;
			
			.time {
				font-size: 24rpx;
				color: #999999;
			}
		}
	}
	
	.load-more {
		text-align: center;
		padding: 30rpx 0;
		color: #666666;
		font-size: 28rpx;
	}
}
</style> 